<template>
  <div class="shop-manage">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-row>
        <el-form-item label="店铺名称">
          <el-input v-model="formInline.shopName" placeholder="输入店铺名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker v-model="formInline.startDate" type="date" placeholder="开始时间" clearable></el-date-picker>
          <el-date-picker v-model="formInline.endDate" type="date" placeholder="结束时间" clearable></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="searchShops">搜索</el-button>
          <el-button type="primary" icon="el-icon-download" @click="exportExcle">下载订单列表</el-button>
        </el-form-item>
      </el-row>
      <el-row>
        <!-- <el-form-item label="订单状态">
          <el-select v-model="formInline.status" placeholder="订单状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option :label="item" :value="index + 1" :key="index + 1" v-for="(item, index) of orderStatus"></el-option>
          </el-select>
        </el-form-item> -->
      </el-row>
    </el-form>
    <el-table
      :data="list"
      v-loading="loading"
      @sort-change="handleSortChange"
      current-row-key="id"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="店铺ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="shopName"
        label="店铺名称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="orderCount"
        sortable
        label="订单总数"
        width="120">
      </el-table-column>
      <el-table-column
        prop="orderPayCount"
        sortable
        :formatter="(row) => formatter(row, 'orderPayCount')"
        label="结算金额">
      </el-table-column>
      <el-table-column
        prop="balance"
        sortable
        :formatter="(row) => formatter(row, 'balance')"
        label="实时余额">
      </el-table-column>
      <el-table-column
        prop="totalWithdraw"
        sortable
        :formatter="(row) => formatter(row, 'totalWithdraw')"
        label="已提取总额">
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      background
      layout="prev, pager, next"
      :page-size="payload.pageSize"
      @current-change="onPageChange"
      :total="payload.total">
    </el-pagination>
  </div>
</template>

<script>
import numeral from 'numeral'
export default {
  name: 'Statistics',
  filters: {
    numChange (val, divide) {
      return numeral(val || 0).divide(divide).format('0.00')
    }
  },
  data () {
    return {
      loading: true,
      payload: {
        current: 1,
        pageSize: 10,
        total: 10,
        orderType: '',
        orderKey: ''
      },
      list: [],
      formInline: {
        status: null,
        startDate: '',
        endDate: '',
        shopName: ''
      }
    }
  },
  methods: {
    handleSortChange ({prop, order}) {
      console.log('prop', prop, order)
      if (!order) {
        this.payload.orderType = ''
      } else if (order === 'descending') {
        this.payload.orderType = 'DESC'
      } else {
        this.payload.orderType = 'ASC'
      }
      this.payload.orderKey = this.payload.orderType ? prop : ''
      this.getStatistics()
    },
    searchShops () {
      this.getStatistics()
    },
    exportExcle () {
      this.loading = true
      let query = {
      }
      if (this.formInline.startDate) query.startDate = this.dateFormat(this.formInline.startDate)
      if (this.formInline.endDate) query.endDate = this.dateFormat(this.formInline.endDate) + ' 23:59:59'
      if (this.formInline.status) query.status = this.formInline.status
      if (this.formInline.shopName) query.shopName = this.formInline.shopName
      // const url = this.ApiUrls.exportExcle + '?query=' + encodeURIComponent(JSON.stringify(query))
      // window.open(url, '_blank')
      this.$http.post(this.ApiUrls.exportExcle, {
        query
      }).then(res => {
        console.log('test res', res)
        if (res.body && res.body.code === 200) {
          window.open('https://qiucc.com/file/' + res.body.body.name, '_blank')
        }
        // this.download(res.body, 'text.xlsx')
      }).catch(err => {
        console.error(err)
      }).finally(() => {
        this.loading = false
      })
    },
    // 创建下载 对象
    download (res, fileName) {
      const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
      if ('download' in document.createElement('a')) {
        console.log('非IE下载')
        const blobUrl = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.download = `${fileName}`
        a.href = blobUrl
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href) // 释放URL 对象
        document.body.removeChild(a) // 移除对象
      } else {
        console.log('IE10+下载')
        // IE10+其他下载
        navigator.msSaveBlob(blob, fileName)
      }
    },
    formatter (row, key) {
      return numeral(row[key] || 0).divide(100).format('0.00')
    },
    getStatistics () {
      this.loading = true
      let query = {
      }
      if (this.formInline.startDate) query.startDate = this.dateFormat(this.formInline.startDate)
      if (this.formInline.endDate) query.endDate = this.dateFormat(this.formInline.endDate) + ' 23:59:59'
      if (this.formInline.status) query.status = this.formInline.status
      if (this.formInline.shopName) query.shopName = this.formInline.shopName
      this.$http.post(this.ApiUrls.shopOrderInfo, {
        query,
        form: {},
        pagination: {
          current: this.payload.current,
          pageSize: this.payload.pageSize,
          orderType: this.payload.orderType,
          orderKey: this.payload.orderKey.replace(/([A-Z])/g, '_$1').toLowerCase()
        }
      }).then(res => {
        console.log('获取数据成功')
        console.log(res)
        if (res.body.code === 200) {
          this.list = res.body.body.map((item) => {
            // item.orderPayCount = numeral(item.orderPayCount || 0).divide(100).format('0.00')
            // item.balance = numeral(item.balance || 0).divide(100).format('0.00')
            // item.totalWithdraw = numeral(item.totalWithdraw || 0).format('0.00')
            item.totalWithdraw = item.totalWithdraw * 100
            return item
          })
          this.payload.total = res.body.pagination.total
        } else {
          this.$message({
            message: '获取数据失败',
            type: 'warning'
          })
        }
      }).catch(err => {
        console.error(err)
      }).finally(() => {
        this.loading = false
      })
      // this.$http.post(`http://${process.env.NODE_ENV === 'development' ? 'localhost:9009' : 'qiucc.com'}/rentmall/statistics/list`, {
      //   query,
      //   form: {},
      //   pagination: {
      //     current: this.payload.current,
      //     pageSize: this.payload.pageSize
      //   }
      // }).then(res => {
      //   console.log('获取数据成功')
      //   console.log(res)
      //   if (res.body.code === 200) {
      //     this.list = res.body.body
      //     this.payload.total = res.body.pagination.total
      //   } else {
      //     this.$message({
      //       message: '获取数据失败',
      //       type: 'warning'
      //     })
      //   }
      // }).catch(err => {
      //   console.error(err)
      // }).finally(() => {
      //   this.loading = false
      // })
    },
    onPageChange (current) {
      this.payload.current = current
      this.getStatistics()
    },
    // 时间格式化
    dateFormat (updateTime) {
      var t = new Date(updateTime)
      var year = t.getFullYear()
      var month = t.getMonth() + 1
      var day = t.getDate()
      var newTime = year + '-' +
          (month < 10 ? '0' + month : month) + '-' +
          (day < 10 ? '0' + day : day)
      return newTime
    }
  },
  mounted () {
    this.getStatistics()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.col {
  display: flex;
  span {
    flex-shrink: 0;
    padding-right: 20px;
    line-height: 40px;
  }
}
.pagination {
  padding-top: 30px;
  margin-left: auto;
  display: table;
}
</style>
